#!/usr/bin/env python3
import os
from launch import LaunchDescription
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
from launch.actions import RegisterEventHandler, EmitEvent, Shutdown
from launch.event_handlers import OnProcessExit

def generate_launch_description():
    package_path = get_package_share_directory("robot_define")
    urdf_file = os.path.join(package_path, "urdf", "robot_simple.urdf")
    rviz__file = os.path.join(package_path, "config", "view.rviz")
    with open(urdf_file, "r") as infp:
        urdf_content = infp.read()

    state_publisher_node = Node(
        package="robot_state_publisher",
        executable="robot_state_publisher",
        name="robot_state_publisher_node",
        output="screen",
        parameters=[{"robot_description": urdf_content}],
    )
    static_tf_node = Node(
        package="tf2_ros",
        executable="static_transform_publisher",
        name="initial_pose_publisher_node",
        output="screen",
        arguments=["0", "0", "0", "0", "0", "0", "map", "chassis"],
    )
    rviz2_node = Node(
        package="rviz2",
        executable="rviz2",
        name="rviz2",
        output="screen",
        arguments=["-d", rviz__file],
    )

    return LaunchDescription(
        [
            state_publisher_node,
            static_tf_node,
            rviz2_node,
            # RegisterEventHandler(
            #    OnProcessExit(
            #        target_action=rviz2_node,
            #        on_exit=[
            #            EmitEvent(event=Shutdown(reason="Window closed")),
            #        ],
            #    )
            # ),
        ]
    )
